package com.dingpeikeji.quickdeer.modules.wx.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.dingpeikeji.quickdeer.modules.wx.driver.vo.Template;
import com.dingpeikeji.quickdeer.modules.wx.driver.vo.TemplateData;
import com.dingpeikeji.quickdeer.modules.wx.driver.vo.WxTemplate;
import com.dingpeikeji.quickdeer.modules.wx.pojo.AccessToken;
import com.dingpeikeji.quickdeer.modules.wx.wxshare.util.CommonUtil;
import com.tencent.common.Configure;

public class WeixinUtil {
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
	public final static String getOpen_id_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	public final static String getRefresh_token_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public final static String sendTemplateMessage_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	

	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;
		String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
			} catch (JSONException e) {
				accessToken = null;
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}"+jsonObject.getString("errmsg"));
			}
		}
		return accessToken;
	}
    /**
     * 检验授权凭证（access_token）是否有效
     * @param accessToken 凭证
     * @param openid id
     * @return
     */
    public static int checkAccessToken(String accessToken, String openid) {
        String requestUrl = "https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openid;
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        int result = 1;
        // 如果请求成功
        if (null != jsonObject) {
            try {
                result = jsonObject.getInt("errcode");
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}");
            }
        }
        return result;
    }
    /**
     * 用户授权，使用refresh_token刷新access_token
     * @return
     */
    public static OpenIdResult getNewAccess_Token(OpenIdResult open,String refresh_token,String openId) {
        String requestUrl = getRefresh_token_url.replace("appid",openId).replace("refresh_token", refresh_token);
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                open.setAccess_token(jsonObject.getString("access_token"));
                open.setExpires_in(jsonObject.getString("expires_in"));
                open.setRefresh_token(jsonObject.getString("refresh_token"));
                open.setOpenid(jsonObject.getString("openid"));
                open.setScope(jsonObject.getString("scope"));
            } catch (JSONException e) {
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}"+jsonObject.getString("errmsg"));
            }
        }
        return open;
    }
    /**
     * 获得用户基本信息
     * @param request
     * @param code
     * @param appid
     * @param appsecret
     * @return
     */
    public static OpenIdResult getOpenId(HttpServletRequest request, String code,String appid, String appsecret) {
        String requestURI = request.getRequestURI();
        String param = request.getQueryString();
        if(param!=null){
            requestURI = requestURI+"?"+param;
        }
        String url = getOpen_id_url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code);
        JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST", null);
        OpenIdResult result = new OpenIdResult();
        if (null != jsonObject) {
            Object obj = jsonObject.get("errcode");
            if (obj == null) {
                result.setAccess_token(jsonObject.getString("access_token"));
                result.setExpires_in(jsonObject.getString("expires_in"));
                result.setOpenid(jsonObject.getString("openid"));
                result.setRefresh_token(jsonObject.getString("refresh_token"));
                result.setScope(jsonObject.getString("scope"));
            }else{
                System.out.println("获取openId回执："+jsonObject.toString()+"访问路径："+requestURI);
                log.error("访问路径:"+requestURI);
                log.error("获取openId失败 errcode:{} errmsg:{}"+jsonObject.getString("errmsg"));
            }
        }
        return result;
    }
    /**
     * 通过网页授权获取用户信息
     * @param accessToken 网页授权接口调用凭证
     * @param openId 用户标识
     * @return WeixinUserInfo
     */
    public static WeixinUserInfo getWeixinUserInfo(String accessToken, String openId) {
        WeixinUserInfo user = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                user = new WeixinUserInfo();
                // 用户的标识
                user.setOpenid(jsonObject.getString("openid"));
                // 昵称
                user.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                user.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                user.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                user.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                user.setCity(jsonObject.getString("city"));
                // 用户头像
                user.setHeadimgurl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                user.setPrivilege(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
            } catch (Exception e) {
                user = null;
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取用户信息失败 errcode:{} errmsg:{}，reqUrl{}"+errorMsg);
            }
        }
        return user;
    }
    /** 
     * 发送模板消息前获取token 
     * @param template_id_short 模板库中模板的编号 
     * @param t 
     * @param m 
     */  
    public static void sendMessageBefore(String template_id_short,WxTemplate t,Map<String,TemplateData> m){  
        AccessToken token = null;  
        if(TokenThread.accessToken==null || TokenThread.accessToken.getToken()==""){  
            //token = WeixinUtil.getAccessToken(TokenThread.appid, TokenThread.appsecret);  
            token = WeixinUtil.getAccessToken(Configure.getAppid(), Configure.getAppsecret());  
        }else{  
        	//测试,正式
            token = TokenThread.accessToken;  
        }  
        if(template_id_short!=null&&!"".equals(template_id_short)){  
            t.setTemplate_id(template_id_short);  
        }  
        t.setData(m);  
        if (token!=null) {
        	WeixinUtil.sendMessage(t,token.getToken());  
		}
    }  
    /** 
     * 发送模板消息 
     * @param t 
     * @param accessToken 
     * @return 
     */  
    public static int sendMessage(WxTemplate t,String accessToken) {  
        int result = 0;  
        // 拼装创建菜单的url  
        String url = sendTemplateMessage_url.replace("ACCESS_TOKEN", accessToken);  
        // 将菜单对象转换成json字符串  
        String jsonMenu = JSONObject.fromObject(t).toString();  
        // 调用接口创建菜单  
        JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST", jsonMenu);  
        if (null != jsonObject) {  
            if (0 != jsonObject.getInt("errcode")) {  
                result = jsonObject.getInt("errcode");  
                log.error("发送模板消息失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
            }  
        }  
        return result;  
    }  
    /** 
     * 获得模板编号获得模板ID 
     * @param template_id_short 
     * @return 
     */  
    public final static String template_id_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";  
    public static Template getTemplate(String template_id_short,String accessToken) {  
        Template template = null;  
        String url = template_id_url.replace("ACCESS_TOKEN",accessToken);  
        String jsonInfo = JSONObject.fromObject(template_id_short).toString();  
        JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST", jsonInfo);  
        if (null != jsonObject) {  
            if (0 == jsonObject.getInt("errcode")) {  
                template = new Template();  
                template.setTemplate_id(jsonObject.getString("template_id"));  
            }else{  
                log.error("获取模板ID失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
            }  
        }  
        return template;  
    }  	
}
